package service

import (
	"errors"
	"gorm.io/gorm/clause"
	"wit-admin-go/system/app/dto"
	"wit-admin-go/system/app/model"
	"wit-admin-go/system/utils"
)

type menuService struct{}

var MenuService = new(menuService)

// PostCreateMenu  创建菜单
func (us *menuService) PostCreateMenu(menu dto.Menu) (err error) {
	return utils.DB.Create(&menu).Error
}

// PutUpdateMenu 修改菜单
func (us *menuService) PutUpdateMenu(menu dto.Menu) (err error) {
	_, errN := us.GetMenuById(menu.Id)
	if errN != nil {
		return errN
	}
	menus := new(model.Menu)
	return utils.DB.Model(&menus).Where("id = ?", menu.Id).Updates(menu).Error
}

// GetMenuById 通过ID查询数据
func (us *menuService) GetMenuById(id string) (menu model.Menu, err error) {
	err = utils.DB.First(&menu, "id = ?", id).Error
	if err != nil {
		return menu, errors.New("数据没找到")
	}
	return menu, err
}

// GetMenuList 获取所有数据
func (us *menuService) GetMenuList(page *dto.MenuPage) (*[]model.Menu, int64) {
	menu := new([]model.Menu)
	db := utils.DB.Preload("CreatorUser").Preload("UpdateUser")
	if page.Name != "" {
		db = db.Where("name LIKE ?", "%"+page.Name+"%")
	}
	if page.Path != "" {
		db = db.Where("path LIKE ?", "%"+page.Path+"%")
	}
	if page.Component != "" {
		db = db.Where("component LIKE ?", "%"+page.Component+"%")
	}
	db = db.Order("sort asc")
	total := db.Scopes(utils.Paginate(page.PageNum, page.PageSize)).Find(&menu).RowsAffected
	if total > 0 {
		return menu, total
	} else {
		return nil, 0
	}
}

// GetTreeList 获取所有数据树
func (us *menuService) GetTreeList(page *dto.MenuPage) ([]*model.Menu, int64) {
	var menu []*model.Menu
	db := utils.DB.Preload(clause.Associations)
	if page.Name != "" {
		db = db.Where("name LIKE ?", "%"+page.Name+"%")
	}
	if page.Path != "" {
		db = db.Where("path LIKE ?", "%"+page.Path+"%")
	}
	if page.Component != "" {
		db = db.Where("component LIKE ?", "%"+page.Component+"%")
	}
	db = db.Order("sort asc")
	//utils.DB.Order("sort asc").Find(&menu)
	total := db.Scopes(utils.Paginate(page.PageNum, page.PageSize)).Find(&menu).RowsAffected
	tree := utils.GetTree("", menu)
	//treeMenu, err := json.Marshal(tree)
	if total > 0 {
		return tree, total
	} else {
		return nil, 0
	}
}

// DelMenu 删除数据
func (us *menuService) DelMenu(id string, userId string) (err error) {
	menu, errN := us.GetMenuById(id)
	if errN != nil {
		return errN
	}
	menu.DeleteId = userId
	err = utils.DB.Delete(&menu, "id = ?", id).Error
	return err
}

// RemoveMenu 删除数据
func (us *menuService) RemoveMenu(id string) (err error) {
	menu := new(model.Menu)
	err = utils.DB.Unscoped().Delete(&menu, "id = ?", id).Error
	return err
}
